package com.sdx.console.stat.controller;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.console.order.service.FinOrderService;
import com.sdx.console.saas.entity.SaasTenant;
import com.sdx.console.stat.entity.StatProductItem;
import com.sdx.console.system.entity.ChannelSet;
import com.sdx.console.system.service.ChannelSetService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName FinTransStatController
 * @Description: 收入统计
 * @author: tanbaocai
 * @date: 2019/2/12 14:23
 */
@RequestMapping("/stat/finTrans")
@Controller
public class FinTransStatController extends AuthorizedBaesController {
	private static final Logger log = LoggerFactory.getLogger(FinTransStatController.class);
	private static final String MODEL = "/stat/finTrans";
	private static final String SQL = "stat.finTrans";

	@Resource
	private SQLManager sqlManager;

    @Resource
    private FinOrderService finOrderService;

    @Resource
    private ChannelSetService channelSetService;

    @Autowired
    private CorePlatformService platformService;

	@GetMapping("/group.do")
	@Function("stat.finTrans.group")
	@ResponseBody
	public ModelAndView group(@RequestParam Map<String,Object> paramMap,String rangeDateQuery,
                              HttpServletRequest request,Integer refundFlag,Integer tenantId) {
		ModelAndView view = new ModelAndView(MODEL+"/group.html");
        Integer accessType = platformService.getAccessType(request);
        CoreUser user = getLoginUser(request);
        view.addObject("accessType",accessType);
        if (accessType==6) {
            SaasTenant param = new SaasTenant();
            param.setTenantStatus(1);
            List<SaasTenant> tenantList = sqlManager.template(param);
            view.addObject("tenantList", tenantList);
        }
		String endDate = null;
		String startDate = null;
		if (StringUtils.isEmpty(rangeDateQuery)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar cal = Calendar.getInstance();
			endDate = sdf.format(cal.getTime());
			cal.add(Calendar.DAY_OF_YEAR,-7);
			startDate = sdf.format(cal.getTime());
		} else {
			String[] pairs = rangeDateQuery.split(" ~ ");
			startDate = pairs[0];
			endDate = pairs[1];
		}
        paramMap.put("refundFlag",refundFlag);
		paramMap.put("startDate",startDate);
		paramMap.put("endDate",endDate);
		paramMap.put("tenantId",user.getTenantId());
		if(accessType==6&&tenantId!=null){
            paramMap.put("tenantId",tenantId);
        }
		view.addObject("startDate",startDate);
		view.addObject("endDate",endDate);
        view.addObject("refundFlag",refundFlag);
		List<BaseEntity> list = sqlManager.select(SQL+".queryGroupStat",BaseEntity.class,paramMap);
		List<StatProductItem> productList = new ArrayList<>();
		StatProductItem productItem = null;
		List<Map<Object,Object>> statList = null;
		Map<Object,Object> mapItem = null;
		String channelName = null;
		Set<String> headSet = null;
		String payDate = "";
		String productName = "";
		for (int i = 0; i < list.size(); i++) {
			BaseEntity be = list.get(i);

			String itemProduct = (String) be.get("dictValue");
			if (StringUtils.isNotEmpty(itemProduct)) {
				if (!itemProduct.equals(productName)) {
					productItem = new StatProductItem();
					statList = productItem.getStatList();
					headSet = productItem.getHeadSet();
					productItem.setProductName(itemProduct);
					productList.add(productItem);
					productName = itemProduct;
				}
				String itemDate = (String) be.get("payDate");
				if (itemDate!=null) {
					if (!itemDate.equals(payDate)) {
						mapItem = new HashMap<>();
						mapItem.put("payDate",itemDate);
						payDate = itemDate;
						statList.add(mapItem);
					}
					channelName = (String) be.get("channelName");
					mapItem.put(channelName,be);
					if (!headSet.contains(channelName)) {
						headSet.add(channelName);
					}
				}
			}
		}
		for (int i = 0; i < productList.size(); i++) {
			productItem = productList.get(i);
			headSet = productItem.getHeadSet();
			productItem.setHeadList(headSet.toArray());
		}
		view.addObject("productList",productList);

		return view;
	}

	@PostMapping("/group.json")
	@Function("stat.finTrans.group")
	@ResponseBody
	public JsonResult<List<BaseEntity>> group()
	{
		List<BaseEntity> list = sqlManager.select(SQL+".queryGroupStat",BaseEntity.class);
		return JsonResult.success(list);
	}

    @GetMapping("/count.do")
    @Function("stat.finTrans.count")
    @ResponseBody
    public ModelAndView count(@RequestParam Map<String,Object> paramMap,String rangeDateQuery,Integer orderType,String channelCode,
            Integer refundFlag,HttpServletRequest request,Integer tenantId) {
        ModelAndView view = new ModelAndView(MODEL+"/count.html");
        Integer accessType = platformService.getAccessType(request);
        CoreUser user = getLoginUser(request);
        view.addObject("accessType",accessType);
        if (accessType==6) {
            SaasTenant param = new SaasTenant();
            param.setTenantStatus(1);
            List<SaasTenant> tenantList = sqlManager.template(param);
            view.addObject("tenantList", tenantList);
        }
        Integer tenantIds = user.getTenantId();
        if(accessType==6&&tenantId!=null){
            tenantIds =tenantId;
        }
        List<ChannelSet> channelList = channelSetService.selectAuthChannels(null, null,tenantIds);
        view.addObject("orderType",orderType);
        view.addObject("channelCode",channelCode);
        view.addObject("channelList",channelList);
        view.addObject("refundFlag",refundFlag);
        view.addObject("orderTypes",finOrderService.selectOrderType(null));
        String endDate = null;
        String startDate = null;
        if (StringUtils.isEmpty(rangeDateQuery)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal = Calendar.getInstance();
            endDate = sdf.format(cal.getTime());
            cal.add(Calendar.DAY_OF_YEAR,-7);
            startDate = sdf.format(cal.getTime());
        } else {
            String[] pairs = rangeDateQuery.split(" ~ ");
            startDate = pairs[0];
            endDate = pairs[1];
        }
        paramMap.put("refundFlag",refundFlag);
        paramMap.put("startDate",startDate);
        paramMap.put("endDate",endDate);
        paramMap.put("orderType",orderType);
        paramMap.put("channelCode",channelCode);
        paramMap.put("tenantId",tenantIds);
        view.addObject("startDate",startDate);
        view.addObject("endDate",endDate);
        List<BaseEntity> list = sqlManager.select(SQL+".queryCountStat",BaseEntity.class,paramMap);
        List<StatProductItem> productList = new ArrayList<>();
        StatProductItem productItem = null;
        List<Map<Object,Object>> statList = null;
        Map<Object,Object> mapItem = null;
        String channelName = null;
        Set<String> headSet = null;
        String payDate = "";
        String productName = "";
        String oldProductName = "";
        if(StringUtils.isNotBlank(channelCode)&&orderType==null){
            for (int i = 0; i < list.size(); i++) {
                BaseEntity be = list.get(i);

                String itemProduct = (String) be.get("channelName");
                if (StringUtils.isNotEmpty(itemProduct)) {
                    if (!itemProduct.equals(productName)) {
                        productItem = new StatProductItem();
                        statList = productItem.getStatList();
                        headSet = productItem.getHeadSet();
                        productItem.setProductName(itemProduct);
                        productList.add(productItem);
                        productName = itemProduct;
                    }
                    String itemDate = (String) be.get("payDate");
                    if (itemDate!=null) {
                        if (!itemDate.equals(payDate)) {
                            mapItem = new HashMap<>();
                            mapItem.put("payDate",itemDate);
                            payDate = itemDate;
                            statList.add(mapItem);
                        }
                        channelName = (String) be.get("orderName");
                        mapItem.put(channelName,be);
                        if (!headSet.contains(channelName)) {
                            headSet.add(channelName);
                        }
                    }
                }
            }
        }else{
            for (int i = 0; i < list.size(); i++) {
                BaseEntity be = list.get(i);

                String itemProduct = (String) be.get("orderName");
                if (StringUtils.isNotEmpty(itemProduct)) {
                    if (!itemProduct.equals(productName)) {
                        productItem = new StatProductItem();
                        statList = productItem.getStatList();
                        headSet = productItem.getHeadSet();
                        productItem.setProductName(itemProduct);
                        productList.add(productItem);
                        productName = itemProduct;
                        payDate = "";
                    }
                    String itemDate = (String) be.get("payDate");
                    if (itemDate!=null) {
                        if (!itemDate.equals(payDate)) {
                            mapItem = new HashMap<>();
                            mapItem.put("payDate",itemDate);
                            payDate = itemDate;
                            statList.add(mapItem);
                        }
                        channelName = (String) be.get("channelName");
                        mapItem.put(channelName,be);
                        if (!headSet.contains(channelName)) {
                            headSet.add(channelName);
                        }
                    }
                }
            }
        }
        for (int i = 0; i < productList.size(); i++) {
            productItem = productList.get(i);
            headSet = productItem.getHeadSet();
            productItem.setHeadList(headSet.toArray());
        }
        view.addObject("productList",productList);
        return view;
    }


    @GetMapping("/static.do")
    @Function("stat.finTrans.statis")
    @ResponseBody
    public ModelAndView statis(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/statis.html");
        Integer accessType = platformService.getAccessType(request);
        view.addObject("accessType",accessType);
        if (accessType==6) {
            SaasTenant param = new SaasTenant();
            param.setTenantStatus(1);
            List<SaasTenant> tenantList = sqlManager.template(param);
            view.addObject("tenantList", tenantList);
        }
        return view;
    }


    @GetMapping("/statis.json")
    @Function("stat.finTrans.statis")
    @ResponseBody
    public JsonResult<List<BaseEntity>> statisYear(HttpServletRequest request)
    {
        Map<String,Object> param = new HashMap<>();
        CoreUser user = getLoginUser(request);
        param.put("tenantId",user.getTenantId());
        List<BaseEntity> list =  new ArrayList<>();
        BaseEntity mouthList = sqlManager.selectSingle(SQL + ".selectPayYear",param, BaseEntity.class);
        BaseEntity successList = sqlManager.selectSingle(SQL + ".selectPaySuccessYear",param, BaseEntity.class);
        BaseEntity baseEntity =  new BaseEntity();
        baseEntity.set("year",2019);
        baseEntity.set("userCount",mouthList.get("userCount"));
        baseEntity.set("payUserCount",successList.get("userCount"));
        baseEntity.set("paySuccessCount",successList.get("count"));
        baseEntity.set("totalMoney",successList.get("totalMoney"));
        list.add(baseEntity);
        return JsonResult.success(list);
    }

    @GetMapping("/statisMouth.json")
    @Function("stat.finTrans.statis")
    @ResponseBody
    public JsonResult<List<BaseEntity>> statisMouth(HttpServletRequest request)
    {
        Map<String,Object> param = new HashMap<>();
        CoreUser user = getLoginUser(request);
        param.put("tenantId",user.getTenantId());
        List<BaseEntity> list =  new ArrayList<>();
        List<BaseEntity> mouthList = sqlManager.select(SQL + ".selectPayMouth", BaseEntity.class,param);
        List<BaseEntity> successList = sqlManager.select(SQL + ".selectPaySuccessMouth", BaseEntity.class,param);
        for (BaseEntity entity : mouthList) {
            BaseEntity baseEntity =  new BaseEntity();
	        baseEntity.set("payUserCount",0);
	        baseEntity.set("paySuccessCount",0);
	        baseEntity.set("totalMoney",0);
            String mouth = "";
            if(entity.get("mouth")!=null){
                mouth =entity.get("mouth").toString();
            }
            baseEntity.set("mouth",entity.get("mouth"));
            baseEntity.set("userCount",entity.get("userCount"));
            for (BaseEntity base : successList) {
                String successMouth = "";
                if(base.get("mouth")!=null){
                    successMouth =base.get("mouth").toString();
                }
                if(mouth.endsWith(successMouth)){
                    baseEntity.set("payUserCount",base.get("userCount"));
                    baseEntity.set("paySuccessCount",base.get("count"));
                    baseEntity.set("totalMoney",base.get("totalMoney"));
                    break;
                }
            }

            list.add(baseEntity);
        }

        return JsonResult.success(list );
    }


	public static void main(String[] args) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_YEAR,-7);
		System.out.println(cal.getTime());
	}
}
